package net.tv90.auth.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import net.tv90.auth.model.AccountToken;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class TokenUtils {

    String secretKey = "tv90666666";

    private final long EXPIRE_TIME_SECOND = 2 * 24 * 60 * 60;

    public String generateToken(String username, String password) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("username", username);
        payload.put("password", password);

        JWT jwt = JWT.create();
        jwt.addPayloads(payload);
        jwt.setKey(secretKey.getBytes());
        jwt.setExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME_SECOND * 1000));

        return jwt.sign();
    }

    public AccountToken parseToken(String token) throws IllegalArgumentException {
        try {
            if(!StrUtil.isEmpty(token) && JWT.of(token).setKey(secretKey.getBytes()).verify()) {
                JWT jwt = JWT.of(token);
                String username = jwt.getPayload("username").toString();
                String password = jwt.getPayload("password").toString();
                if(username != null && password != null) {
                    return new AccountToken(username, password);
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("token不合法");
        }
        throw new IllegalArgumentException("token校验失败");
    }

    /**
     * 供业务服务器调用，先解析JWT令牌是否合法，如合法再请求认证服务器校验
     * @param token JWT令牌
     * @return 是否合法
     */
    public boolean validToken(String token) {
        try {
            if(!StrUtil.isEmpty(token) && JWT.of(token).setKey(secretKey.getBytes()).verify()) {
                JWT jwt = JWT.of(token);
                String username = jwt.getPayload("username").toString();
                String password = jwt.getPayload("password").toString();
                if(username != null && password != null) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
